<template>
  <div class="container">
    <!-- 帖子部分 -->
    <div class="post-section">
      <div class="post-container">
        <div class="post-content" v-if="postDetails">
          <h1 class="post-title">{{ postDetails.title }}</h1>
          <div class="post-meta">
            <div class="author-info">
              <span class="username">{{ postDetails.user.username }}</span>
              <span class="post-date">{{ new Date(postDetails.created_at).toLocaleDateString() }}</span>
            </div>
            <button
              class="like-btn"
              :class="{ 'is-liked': postDetails.liked }"
              @click="likePost"
            >
              <span class="like-icon">👍</span>
              <span class="like-count">{{ postDetails.likes }}</span>
            </button>
          </div>
          <div class="post-text">
            {{ postDetails.content }}
          </div>
        </div>
      </div>
    </div>

    <!-- 评论部分 -->
    <div class="comments-section">
      <div class="comments-header">
        <h2>评论区</h2>
        <span class="comment-count">{{ comments.length }}条评论</span>
      </div>
      
      <div class="comments-list">
        <div v-if="comments && comments.length > 0">
          <div v-for="(comment, index) in comments" 
               :key="comment.id" 
               class="comment-item">
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-footer">
              <div class="comment-meta">
                <span class="comment-username">{{ comment.user?.username || '匿名' }}</span>
                <span class="comment-time">{{ new Date(comment.created_at).toLocaleDateString() }}</span>
              </div>
              <button
                class="comment-like-btn"
                :class="{ 'is-liked': comment.liked }"
                @click="likeComment(index)"
              >
                <span class="like-icon">👍</span>
                <span class="like-count">{{ comment.likes }}</span>
              </button>
            </div>
          </div>
        </div>
        <div v-else class="no-comments">暂无评论</div>
      </div>

      <div class="comment-input-section">
        <textarea 
          v-model="newComment.content" 
          placeholder="写下你的评论..."
          class="comment-textarea"
        ></textarea>
        <button class="submit-btn" @click="createPostComment">发表评论</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  fetchPostDetails,
  fetchPostComments,
  createComment,
  likeComment as apiLikeComment,
  likePost as apiLikePost, 
  getCommentLikeStatus,
  getPostLikeStatus,

} from '../services/commuServ'
import { useRoute } from 'vue-router'
import { success, error } from '../tools/messageBox'
import {getUser } from "../services/userServ"


const route = useRoute()
const postDetails = ref(null)
const comments = ref([])
const newComment = reactive({ content: '' })
const user = getUser()

// 点赞帖子
const likePost = async () => {
  try {
    const response = await apiLikePost(postDetails.value.id)
    postDetails.value.likes = response.likes_count
    postDetails.value.liked = response.liked
    success(response.liked ? '点赞成功' : '取消点赞成功')
  } catch (err) {
    error('操作失败: ' + (err.response?.data?.message || '未知错误'))
  }
}

// 点赞评论
const likeComment = async (index) => {
  try {
    const comment = comments.value[index]
    const response = await apiLikeComment(comment.id)
    comments.value[index].likes = response.likes_count
    comments.value[index].liked = response.liked
    success(response.liked ? '点赞成功' : '取消点赞成功')
  } catch (err) {
    error('操作失败: ' + (err.response?.data?.message || '未知错误'))
  }
}

// 发布评论
const createPostComment = async () => {
  if (!newComment.content.trim()) {
    error('评论内容不能为空')
    return
  }
  try {
    const user = await getUser()
    const userId = user.id || user.user_id // 确保获取到用户ID
    //console.log('当前用户ID:', userId)
    const commentData = {
      content: newComment.content,
      post_id: route.params.id,
      user_id: userId
    }
    console.log('发布评论数据:', commentData)
    const res = await createComment(commentData)
    comments.value.unshift(res)
    newComment.content = ''
    success('发布成功')
  } catch (err) {
    error('发布失败: ' + (err.response?.data?.message || '未知错误'))
  }
}

// 在加载帖子详情时获取点赞状态
const loadPostDetails = async () => {
  try {
    const response = await fetchPostDetails(route.params.id)
    console.log('获取的帖子详情:', response)
    const likeStatus = await getPostLikeStatus(route.params.id)
    console.log('获取的帖子点赞状态:', likeStatus)
    postDetails.value = {
      ...response,
      liked: likeStatus.liked,
      likes: likeStatus.likes_count
    }
  } catch (err) {
    error('加载帖子失败: ' + (err.response?.data?.message || '未知错误'))
  }
}

// 在加载评论时获取点赞状态
const loadComments = async () => {
  try {
    console.log('加载评论，帖子ID:', route.params.id)
    const response = await fetchPostComments(route.params.id)
    console.log('获取的评论:', response)
    const commentsWithLikes = await Promise.all(
      (response || []).map(async (comment) => {
        const likeStatus = await getCommentLikeStatus(comment.id)
        //console.log(`评论 ${comment.id} 的点赞状态:`, likeStatus)
        return {
          ...comment,
          liked: likeStatus.liked,
          likes: likeStatus.likes_count
        }
      })
    )
    comments.value = commentsWithLikes
  } catch (err) {
    error('加载评论失败: ' + (err.response?.data?.message || '未知错误'))
  }
}

onMounted(async () => {
  await loadPostDetails()
  await loadComments()
})
</script>


<style scoped>
.container {
  display: flex;
  width: 100%;
  min-height: 100vh;
  background: #f6f8fa;
  gap: 24px;
  padding: 24px;
}

/* 帖子部分样式 */
.post-section {
  flex: 1;
  max-width: 800px;
}

.post-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  padding: 32px;
}

.post-title {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 24px;
  line-height: 1.4;
}

.post-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eef2f7;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.username {
  font-size: 1.1rem;
  color: #2c3e50;
  font-weight: 500;
}

.post-date {
  color: #8492a6;
  font-size: 0.9rem;
}

.post-text {
  font-size: 1.1rem;
  line-height: 1.8;
  color: #34495e;
  margin-bottom: 32px;
}

.like-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 24px;
  border: none;
  border-radius: 20px;
  background: #f5f7fa;
  cursor: pointer;
  transition: all 0.3s ease;
}

.like-btn.is-liked {
  background: #ffeee6;
  color: #e17055;
}

/* 评论区样式 */
.comments-section {
  width: 400px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 48px);
}

.comments-header {
  padding: 24px;
  border-bottom: 1px solid #eef2f7;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comments-header h2 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin: 0;
}

.comment-count {
  color: #8492a6;
  font-size: 0.9rem;
}

.comments-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.comment-item {
  padding: 16px;
  border-bottom: 1px solid #eef2f7;
}

.comment-content {
  font-size: 0.95rem;
  line-height: 1.6;
  color: #34495e;
  margin-bottom: 12px;
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comment-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.comment-username {
  font-size: 0.9rem;
  color: #2c3e50;
  font-weight: 500;
}

.comment-time {
  font-size: 0.8rem;
  color: #8492a6;
}

.comment-like-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 16px;
  border: none;
  border-radius: 16px;
  background: #f5f7fa;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.comment-like-btn.is-liked {
  background: #ffeee6;
  color: #e17055;
}

.comment-input-section {
  padding: 20px;
  border-top: 1px solid #eef2f7;
  background: #fff;
  border-radius: 0 0 12px 12px;
}

.comment-textarea {
  width: 100%;
  height: 80px;
  padding: 12px;
  border: 1px solid #e5e9ef;
  border-radius: 8px;
  resize: none;
  margin-bottom: 12px;
  font-size: 0.95rem;
  transition: border-color 0.3s ease;
}

.comment-textarea:focus {
  border-color: #409eff;
  outline: none;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 8px;
  background: #409eff;
  color: white;
  font-size: 0.95rem;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease;
}

.submit-btn:hover {
  background: #66b1ff;
}

.no-comments {
  text-align: center;
  color: #8492a6;
  padding: 32px 0;
}

/* 滚动条样式 */
.comments-list::-webkit-scrollbar {
  width: 6px;
}

.comments-list::-webkit-scrollbar-track {
  background: #f6f8fa;
}

.comments-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.comments-list::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>